package me.sealer.jmx.util;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

/**
 * @author sealer
 * @date 2018/01/22.
 */
public class LogLevelUtil {
    public static final String DOMAIN_NAME = "me.sealer.jmx";
    public static final String RELOAD_CONFIG_NAME = "reloadConfig";

    /**
     * 改变日志级别 jmx
     *
     * @param logger logger
     * @param level  要修改为的级别
     * @return 0-修改成功； -1-修改失败。
     */
    public static int changeLogLevel(String logger, String level) throws Exception {
        //connect JMX
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:8888/logback_config");
        JMXConnector jmxConnector = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
        ObjectName mbeanName = new ObjectName(DOMAIN_NAME + ":name=" + RELOAD_CONFIG_NAME);

        //invoke via rmi
        mBeanServerConnection.invoke(mbeanName, "setLoggerLevel", new Object[]{logger, level}, new String[]{String.class.getName(), String.class.getName()});
        jmxConnector.close();

        // 先把返回值写死吧
        return 0;
    }
}
